<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pages extends CI_Controller {
    function __construct(){
        parent::__construct();
        $this->load->model('pages_model', 'p');
    }

    function index(){
        $data['result']  = $this->p->get_many_by(array('delete_flag' => UNDELETE_FLAG, 'draft' => DRAFT_NO));
        $data['tpl']     = 'admin/pages/index';
        $this->load->view('layout/master', $data);
    }

    function add(){
        $this->_update();
    }

    function edit($id = 0){
        $this->_update($id);
    }

    function _update($id = 0){
        $id = intval($id);
        $edit_flag = $id != 0 ? true : false;

        if ($_POST){
            $id = intval($this->input->post('id'));
            $info = array(
                'title'        => trim($this->input->post('title')),
                'url_friendly' => mb_convert_case(url_title(loc_dau(trim($this->input->post('title')))), MB_CASE_LOWER, 'utf-8'),
                'type'         => intval($this->input->post('type')),
                'intro'        => trim($this->input->post('intro')),
                'content'      => trim($this->input->post('content')),
                'update_date'  => date('Y-m-d H:i:s', time()),
                'draft'        => DRAFT_NO
            );
            $result = $this->p->update($id, $info);

            if ($edit_flag){
                $data['msg'] = 'Lưu trang thành công';
            } else {
                $data['msg'] = 'Thêm mới trang thành công';
            }
        }

        if ($edit_flag){
            $data['data'] = $this->p->get($id);
        } else {
            //Check draft
            $exist = $this->p->get_by(array('draft' => DRAFT_YES, 'user_id' => $_SESSION['admin']['id']));
            if (count($exist) > 0){
                $data['data'] = $exist;
            } else {
                $draft = array('draft' => DRAFT_YES, 'user_id' => $_SESSION['admin']['id'], 'update_date' => date('Y-m-d H:i:s'), 'create_date' => date('Y-m-d H:i:s'));
                $this->p->insert($draft);
                $data['data'] = $draft;
            }
        }

        //Category
        $data['tpl'] = 'pages/edit';
        $this->load->view('layout/master', $data);
    }

    function delete(){
        if ($_POST){
            $id = $this->input->post('id');
            if (is_array($id)){
                $id = array($id);
            }
            $result = $this->p->update_many($id, array('delete_flag' => DELETE_FLAG));
            echo $result;
        }
    }
}